package com.leza.myapplication.ui.dashboard;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.leza.myapplication.R;
import com.leza.myapplication.ui.home.HomeFragment;

public class DashboardFragment extends Fragment {

    private WebView webView;
    private ImageButton webButton;
    private HomeFragment homeFragment;

    @SuppressLint("SetJavaScriptEnabled")
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
        webView = (WebView) root.findViewById(R.id.webview_dashboard);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new MyWebViewClient());
        webView.loadUrl("https://open.iot.10086.cn/onenetview/presentation.html#/?mode=share&tabno=0&s=b8e17bfd3c0d4dc9");

        webView.setOnKeyListener((v, keyCode, event) -> {
            if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
                webView.goBack();
                return true;
            }
            return false;
        });

        webButton = root.findViewById(R.id.web_button);
        webButton.setOnClickListener(u -> {
            if (homeFragment == null) {
                homeFragment = new HomeFragment();
            }
            requireActivity().getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, homeFragment).commitAllowingStateLoss();
            homeFragment.TimerRefreshStop();
            System.out.println("正在切换到网页");
        });

        return root;
    }

    class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            return super.shouldOverrideUrlLoading(view, request);
        }
    }


}